package com.tecode.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tecode.bean.User;
import com.tecode.bean.UserFans;
import com.tecode.bean.UserRejection;
import com.tecode.service.MusicService;
import com.tecode.service.UserRejectionService;
import com.tecode.service.UserService;
import com.tecode.util.UrlUtil;
import com.tecode.util.WXBizDataCrypt;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@Controller
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserRejectionService userRejectionService;
    @Autowired
    private MusicService musicService;

    /**
     * 通过音乐人id获取其作品详情
     */
    @RequestMapping("/get/works/{id}")
    public String toShowWorks(@PathVariable("id") Integer id,Model model){
        if (id!=null || id!=0){
             model.addAttribute("works",userService.getWorksByid(id));
             model.addAttribute("worksNum",userService.selectMusicUserWorksNumById(id));
        }
        return "works-show.html";
    }

    /**
     * 查询审核详情
     */
    @RequestMapping("/member-show1.html/{id}")
    public String toShow1(Model model,@PathVariable("id") Integer id){
        if (id!=0 || id!=null){
            if(userService.selectExamineInfoById(id)!=null){
                model.addAttribute("infos",userService.selectExamineInfoById(id));
            }
        }
        return "member-show1.html";
    }

    /**
     * 添加审核用户
     * @param id
     * @param reason
     * @return
     */
    @RequestMapping("/insert/reject")
    @ResponseBody
    public boolean insertReject(Integer id,String session,String reason){
        boolean result = false;
        UserRejection userRejection = new UserRejection();
        userRejection.setAdmin(session);
        userRejection.setUserid(id);
        userRejection.setReason(reason);
        if(userService.updateRejectById(id)>0 && userRejectionService.insertReject(userRejection)>0){
            result =true;
        }
        return result;
    }

    /**
     * 进入驳回原因编辑
     * @param model
     * @param id
     * @return
     */
    @RequestMapping("/member-add.html/{id}")
    public String toMemberAdd(Model model,@PathVariable("id") Integer id){
        model.addAttribute("id",id);
        return "member-add.html";
    }

    /**
     * 进入通过原因编辑
     * @param model
     * @param id
     * @return
     */
    @RequestMapping("/member-add1.html/{id}")
    public String toMemberAdd1(Model model,@PathVariable("id") Integer id){
        model.addAttribute("id",id);
        return "member-add1.html";
    }

    /**
     * 通过id审核user
     * @param id
     * @return
     */
    @RequestMapping("/lookThrough/user")
    @ResponseBody
    public boolean lookThroughUser(Integer id,String session,String reason){
        boolean result = false;
        UserRejection userRejection = new UserRejection();
        userRejection.setAdmin(session);
        userRejection.setUserid(id);
        userRejection.setReason(reason);
        if (userService.lookThroughUserById(id)>0 && userRejectionService.insertReject(userRejection)>0 && userService.updateUserCodeIdById(id)>0){
            result=true;
        }
        return result;
    }

    /**
     * 获取审核状态下的user（包括待审核，审核通过，审核未通过）
     * @return
     */
    @RequestMapping("/member-del.html")
    public String getNoExamineUser(Model model){
        model.addAttribute("lists",userService.selectUserByType());
        model.addAttribute("num",userService.selectUserByTypeNum());
        return "member-del";
    }

    /**
     * 通过id单个修改user.typeId(删除)
     * @param id
     * @return
     */
    @RequestMapping("/update/user/{id}")
    @ResponseBody
    public boolean updateUserById(@PathVariable("id") Integer id){
        boolean result = false;
        if(userRejectionService.selectUserTypeIdById(id) != 11){
            if (userService.updateUserById(id)>0){
                result=true;
            }
        }
        return result;
    }

    /**
     * 批量修改user.typeId
     * @param ids
     * @return
     */
    @RequestMapping(value = "/batch/update/user")
    @ResponseBody
    public boolean batchUpdateUser(@RequestParam(value = "ids[]") Integer ids[]){
        int count =0;
        boolean result = false;
        if (ids.length != 0){
            for (int i=0; i<ids.length; i++){
                if (userRejectionService.selectUserTypeIdById(ids[i]) !=11){
                    count++;
                }
                if(count==ids.length){
                    for(int j=0; j<ids.length; j++){
                        userService.updateUserById(ids[j]);
                    }
                    result=true;
                }
            }
        }
        return result;
    }

    /**
     * 查询所有user
     * @param model
     * @return
     */
   @RequestMapping("/member-list.html")
    public String getAllUser(Model model){
       int userNum=0;
       int musicNum=0;
       for (int i=0; i<userService.selectUserByCodeNum().size(); i++){
           if (userService.selectUserByCodeNum().get(i).get("NAME").toString().equals("普通")){
               Long user =(Long) userService.selectUserByCodeNum().get(i).get("人数");
               userNum = Math.toIntExact(user);
           }
           if (userService.selectUserByCodeNum().get(i).get("NAME").toString().equals("音乐人")){
               Long music = (Long) userService.selectUserByCodeNum().get(i).get("人数");
               musicNum = Math.toIntExact(music);
           }
       }
       model.addAttribute("num",userNum+musicNum);
       model.addAttribute("user",userService.getAllUser());
        return "member-list.html";
    }

    /**
     * 通过id获取user详情
     * @param model
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public String getUserInfo(Model model ,@PathVariable("id") Integer id){
       if (userService.selectUserById(id)!= null){
           model.addAttribute("userId",id);
           model.addAttribute("infos",userService.selectUserById(id));
           model.addAttribute("worksNum",userService.selectMusicUserWorksNumById(id));
       }
       return "member-show.html";
    }

    /**
     * 拉取微信信息（openid,session_key）
     * @param code
     * @param encryptedData
     * @param iv
     * @return
     */
    @GetMapping("/getWxUserInfo")
    @ResponseBody
    public Object getWxUserInfo(@RequestParam String code,@RequestParam String encryptedData,@RequestParam String iv){
        Map map = new HashMap();
        String appId = "wx305eb37ef684f6da";
        String appSecret = "17c56721d1143905f221e37d414ccb47";
        String apiUrl = "https://api.weixin.qq.com/sns/jscode2session";
        String sessionId = "";
        Map<String,String> requestUrlParam = new HashMap<String,String>();
        requestUrlParam.put("appid", appId);//开发者设置中的appId  
        requestUrlParam.put("secret", appSecret); //开发者设置中的appSecret  
        requestUrlParam.put("js_code", code); //小程序调用wx.login返回的code  
        requestUrlParam.put("grant_type", "authorization_code");//默认参数 
        JSONObject jsonObject = JSON.parseObject(UrlUtil.sendPost(apiUrl, requestUrlParam));
        String openid = jsonObject.get("openid").toString();
        String session_key = jsonObject.get("session_key").toString();


        if (jsonObject.get("openid")!=null&&jsonObject.get("session_key")!=null){
            Map userByOpenid = userService.getUserByOpenid(openid);
            try {
                String wxUser = WXBizDataCrypt.openPassword(session_key, encryptedData, iv);
                if (userByOpenid==null){
                    JSONObject userJson = JSONObject.parseObject(wxUser);
                    User user = new User();
                    user.setCreatetime(new Date());
                    user.setOpenid(openid);
                    user.setCodeid(14);
                    user.setHead(userJson.getString("avatarUrl"));
                    user.setNickname(userJson.getString("nickName"));
                    user.setSex(userJson.getInteger("gender"));
                    userService.addUser(user);
                    map.put("user",user);
                }else{
                    Integer concerns = userService.getConcernCount((Integer) userByOpenid.get("userId"));
                    Integer fans = userService.getFansCount((Integer) userByOpenid.get("userId"));
                    userByOpenid.put("concerns",concerns);
                    userByOpenid.put("fans",fans);
                    map.put("user",userByOpenid);
                }

                ValueOperations valueOperations = redisTemplate.opsForValue();
                sessionId = UUID.randomUUID().toString();
                valueOperations.set(sessionId,jsonObject);
                map.put("sessionId",sessionId);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return JSONObject.toJSON(map);
    }

    /**
     * 用户进入小程序时的验证方法，判断登录时效是否有效
     * @param sessionId
     * @return
     */
    @GetMapping("/verUser")
    @ResponseBody
    public boolean verWxUser(@RequestParam String sessionId){
        ValueOperations valueOperations = redisTemplate.opsForValue();
        Object sessionId1 = valueOperations.get(sessionId);
        if (StringUtils.isNotEmpty(sessionId)){
            return true;
        }
        return false;
    }

    /**
     * 获取用户关注的分类列表
     * @param userId
     * @return
     */
    @ResponseBody
    @GetMapping("/getConcernList")
    public List getConcernList(@RequestParam Integer userId){
        return userService.getConcernList(userId);
    }

    /**
     * 手机号验证码登录
     * @param phone
     * @param ver
     * @param map
     * @return
     */
    @GetMapping("/phoneLogin")
    @ResponseBody
    public Object phoneLogin(@RequestParam String phone,@RequestParam String ver,Map map){
        String sessionId = "";
        Date now = new Date();
        Map user = userService.getUserByPhone(phone);

        if (user!=null){
            if(StringUtils.isNotEmpty(ver)&&ver.equals(user.get("ver"))){
                Date ver_deadline = (Date) user.get("ver_deadline");
                if (now.after(ver_deadline)){
                    map.put("verOutTime","验证码已过期");
                }else{
                    ValueOperations valueOperations = redisTemplate.opsForValue();
                    sessionId = UUID.randomUUID().toString();
                    valueOperations.set("sessionId",sessionId);
                    map.put("sessionId",sessionId);
                    map.put("user",user);
                }
            }else{
                map.put("verError","验证码错误！");
            }
        }
        return JSONObject.toJSON(map);
    }

    /**
     * 获取手机验证码
     * @param phone
     * @param map
     * @return
     */
    @GetMapping("/getVer")
    @ResponseBody
    public Object getVer(@RequestParam String phone,Map<String,Object> map){
        Map user = userService.getUserByPhone(phone);
        if (user!=null){
            System.out.println(true);
            String ver = userService.getVer(phone);
            map.put("ver",ver);
        }else {
            System.out.println(false);
            map.put("msg","该手机号尚未绑定！");
        }


        return JSONObject.toJSON(map);
    }

    /**
     * 修改用户信息
     * @param user
     * @return
     */
    @PutMapping("saveUser")
    @ResponseBody
    public Object save(@RequestBody User user){
        int save = userService.save(user);
        if (save>0){
            List<Object> objects = userService.selectUserById(user.getUserId());
            return objects;
        }
        return null;
    }

    /**
     * 取消关注
     * @param userFans
     * @return
     */
    @DeleteMapping("cancelConcern")
    @ResponseBody
    public boolean cancelConcern(@RequestBody UserFans userFans){
        int del = userService.del(userFans.getUserId(),userFans.getFansId());
        return del > 0 ? true : false;
    }

    /**
     * 获取热门音乐人列表
     * @return
     */
    @GetMapping("hostMusicMan")
    @ResponseBody
    public List hostMusicMan(){
        return userService.selectUserListDay();
    }

    /**
     * 访问用户主页
     * @param userId
     * @param map
     * @return
     */
    @GetMapping("man")
    @ResponseBody
    public Object getUserDetailsByUserId(@RequestParam Integer userId,Map map){
        Map user = userService.getUserDetailsByUserId(userId);
        List<Map> musics = musicService.getMusicsByUserId(userId);
        List fans = userService.getFansByUserId(userId);
        map.put("fans",fans);
        map.put("user",user);
        map.put("musics",musics);
        return JSONObject.toJSON(map);

    }

    /**
     * 监听用户主页访问
     * @param trafficVolume
     * @param userId
     * @return
     */
    @GetMapping("trafficVolumeListener")
    @ResponseBody
    public boolean trafficVolumeListener(@RequestParam Integer trafficVolume,@RequestParam Integer userId){
        int i = userService.trafficVolumeListener(trafficVolume, userId);
        return i>0 ? true:false;
    }

    /**
     * 添加用户关注
     * @param userFans
     * @return
     */
    @PostMapping("addUserFans")
    @ResponseBody
    public boolean addUserFans(@RequestBody UserFans userFans){
        int i = userService.addUserFans(userFans);
        return i>0?true:false;
    }

    @GetMapping("getFansList")
    @ResponseBody
    public List getFansList(@RequestParam Integer userId){
        List fans = userService.getFansList(userId);
        return fans;
    }
}
